<?php
/**
 * Created by PhpStorm.
 * User: Knight
 * Date: 2018/10/23
 * Time: 17:05
 */

namespace app\api\util;


class CurlRequest
{
    /**Curl请求get方法
     *@$url     String  要请求的url地址
     *@$dara    Array   要传递的参数
     *@$timeout int     超时时间
     * @return   json
     */
    function curlGetRequest($url = '', $data = array(), $timeout = 10)
    {
        if ($url == '' || $timeout <= 0) {
            return false;
        }
        $param = '';
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $param .= $k . '=' . $v . '&';
            }
            $param = rtrim($param, '&');
            $url = $url . '?' . $param;
        }

        $con = curl_init();
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

        $output = curl_exec($con);
        curl_close($con);

        return $output;
    }


    /**Curl请求Post方法
     *@$url     String  要请求的url地址
     *@$dara    Array   要传递的参数
     *@$timeout int     超时时间
     * @return   json
     */
    function curlPostRequest($url = '', $data = array(), $timeout = 10)
    {
        if ($url == '' || empty($data) || $timeout <= 0) {
            return false;
        }

        $param = '';
        foreach ($data as $k => $v) {
            $param .= $k . '=' . $v . '&';
        }
        $param = rtrim($param, '&');

        $con = curl_init();
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_POSTFIELDS, $param);
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
        $output = curl_exec($con);
        curl_close($con);

        return $output;
    }

    /**
     * http请求
     * @return mixed
     */
    public function httpGet($url){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($curl,CURLOPT_TIMEOUT,500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}